package com.dailywork.basepro.xml;

import com.dailywork.basepro.xml.model.Book;
import org.apache.log4j.Logger;
import org.w3c.dom.Document;
import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * @author think
 * @version 2019/10/20
 * @since 通过Dom的方式读取xml文件
 */
public class ReadxmlByDom {

    private static Logger logger = Logger.getLogger(ReadxmlByDom.class);

    private static DocumentBuilderFactory documentBuilderFactory = null;
    private static DocumentBuilder documentBuilder = null;
    private static Document document = null;

    private static List<Book> bookList = null;

    static {
        try {
            documentBuilderFactory = DocumentBuilderFactory.newInstance();
            documentBuilder = documentBuilderFactory.newDocumentBuilder();
        } catch (ParserConfigurationException e) {
            logger.error("Init error: ", e);
        }
    }

    public static List<Book> getBookList(String fileName) {
        try {
            document = documentBuilder.parse(fileName);
            NodeList nodeList = document.getElementsByTagName("book");
            bookList = new ArrayList<>();
            for (int i = 0; i < nodeList.getLength(); i++) {
                Book book = new Book();
                Node node = nodeList.item(i);
                NamedNodeMap namedNodeMap = node.getAttributes();

                String id = namedNodeMap.getNamedItem("id").getTextContent();
                book.setId(Integer.parseInt(id));

                NodeList nodeList1 = node.getChildNodes();
                List<String> contents = new ArrayList<>();
                for (int j = 1; j < nodeList1.getLength(); j++) {
                    Node node1 = nodeList1.item(j);
                    String content = node1.getFirstChild().getTextContent();
                    contents.add(content);
                }
                book.setName(contents.get(0));
                book.setAuthor(contents.get(1));
                book.setYear(Integer.parseInt(contents.get(2)));
                book.setPrice(Integer.parseInt(contents.get(3)));
                bookList.add(book);
            }

        } catch (IOException | SAXException e) {
            logger.error("Xml parse error: ", e);
        }
        return bookList;
    }

    public static void main(String[] args) {
        String fileName = "src/res/books.xml";
        try {
            List<Book> list = ReadxmlByDom.getBookList(fileName);
            for (Book book : list) {
                System.out.println(book);
            }
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
}
